package com.core.cloudgateway.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.core.cloudcommon.CommonCustomException;
import com.core.cloudcommon.redis.service.CloudRedisTemplateService;
import com.core.cloudcommon.redis.vo.CloudRedisVO;
import com.core.cloudcommon.security.ConcurrentLoginManager;
import com.core.cloudcommon.security.JwtTokenUtil;
import com.core.cloudgateway.enums.CloudGatewayResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.Objects;

/**
 * @author =====Lqj=====
 * @className CloudGatewayAuthorizeService
 * @description 网关过滤器
 * @create 2024/11/12 19:53
 **/

@Component
public class CloudGatewayAuthorizeService implements GlobalFilter, Ordered {

    @Autowired
    private CloudRedisTemplateService cloudRedisTemplateService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private ConcurrentLoginManager concurrentLoginManager;

    /**
     * 获取此对象的 order 值。
     * 较高的值被解释为较低的优先级。因此，具有最低值的对象具有最高优先级（有点类似于 Servlet load-on-startup 值）。
     * 相同的 order 值将导致受影响对象的任意排序位置。
     * 返回：订单值
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 网关过滤器
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //先获取请求信息
        ServerHttpRequest request = exchange.getRequest();

        String path = request.getURI().getPath();
        if ("/api/cloud/sys/login".equals(path) || "/api/cloud/sys/sendSms".equals(path)) {
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst("token");
        if (Objects.isNull(token)) {
            throw new CommonCustomException(CloudGatewayResultCode.CODE400002.getCode(),
                                          CloudGatewayResultCode.CODE400002.getMsg());
        }

        try {
            // JWT Token验证
            if (jwtTokenUtil.isTokenExpired(token)) {
                throw new CommonCustomException(CloudGatewayResultCode.CODE400001.getCode(),
                                              "Token已过期，请重新登录");
            }

            // 并发登录验证
            if (!concurrentLoginManager.isTokenValid(token)) {
                throw new CommonCustomException(CloudGatewayResultCode.CODE400001.getCode(),
                                              "Token已失效，请重新登录");
            }

            // 更新设备活跃时间
            concurrentLoginManager.updateDeviceActiveTime(token);

            // 检查是否需要刷新token（可选，在响应头中提示前端）
            if (jwtTokenUtil.shouldRefreshToken(token)) {
                ServerHttpResponse response = exchange.getResponse();
                response.getHeaders().add("X-Token-Refresh-Needed", "true");
            }

        } catch (CommonCustomException e) {
            throw e;
        } catch (Exception e) {
            throw new CommonCustomException(CloudGatewayResultCode.CODE400003.getCode(),
                                          "Token验证失败");
        }
        return chain.filter(exchange);
    }
}
